/*
    This clas is base class for all  other control, such as: MasterPage, Page, UserControl
    To enable control to auto refresh, we need to set these value:
        refreshInterval: number of milisecond that control will auto refresh
        isAutoRefresh:true to enable auto refresh, false to disbale auto refresh
*/
Global.namespace("System.Core.UI");

System.Core.UI.BaseControl=function(config){
    try{
        System.Core.UI.BaseControl.numOfControl+=1;
        this.id=StringHandler.format("{0}{1}","basewebcontrol",System.Core.UI.BaseControl.numOfControl);
        // apply custome properties
        Global.apply(this,config);
        if(!System.Core.UI.BaseControl.numOfControl){
            System.Core.UI.BaseControl.numOfControl=0;
        }
        // auto increse when new control was created

        // array of child control of current control
        this.controls=new Array();
        // init control
        this.onInitializing();
        this.initialize();
        this.onInitialized();
    }catch(e){
        e.source="BaseControl constructor";
        ExceptionHandler.throwEx(e);
    }
};

System.Core.UI.BaseControl.prototype = {
    // auto increment id
    id: '',
    // reference to parent of control
    parent: null,
    // true if control was loaded
    isLoaded: false,
    // true if control will auto refresh its content after interval
    isAutoRefresh: false,
    // value indecate that control content will refreshed after 'refreshInterval' milisecond
    refreshInterval: 0,
    // jquery selector format of wrapper that  control will be rendered into
    wrapper: "",
    templateFile: null,
    // html of control that will be inserted into control wrapper container
    innerHtml: "tet html",
    template: "<div id='{0}'></div>",
    /* methods */
    add: function(control) {
        if (!control) { return; }
        control.parent = this;
        this.controls[this.controls.length] = control;
    },
    remove: function(controlId) {
        for (var index = 0; index < this.controls.length; index++) {
            if (this.controls[index].id !== controlId) { continue; }
            this.controls[index] = this.controls[this.controls.length - 1];
            this.controls.length -= 1;
        }
    },
    removeAll: function() {
        this.controls = new Array();
    },
    /* Event */
    // methods was called when error occured inside control
    onError: function(e) {
        e.source = "onError methods";
        ExceptionHandler.throwEx(e);
    },
    // methods was called before control was initialized
    onInitializing: function() { },
    // initialized control
    initialize: function() { },
    // methods was called after control was initialized
    onInitialized: function() { },
    onLoading:function(){},
    // load control
    load: function() { },
    // methods was called before control was rendered
    onRendering: function() { },
    // render control
    renderControl: function() {
        try {
            
            this.load();
            this.onRendering();
            var html = Global.applyBookmarks(this.innerHtml); //StringHandler.format(this.template,this.id,this.innerHtml);
            // if wrapper container was not found. append content into body of page
            $('#' + this.id).html(html);
            for (var index = 0; index < this.controls.length; index++) {
                if (!this.controls[index].render) { continue; }
                // render child control
                this.controls[index].render();
            }
            //
            this.onRendered();
        } catch (e) {
            e.source = "Base control render";
            ExceptionHandler.throwEx(e);
        }
    },
    render: function(wrapper) {
        
        this.template = StringHandler.format(this.template, this.id);
        if ($(this.wrapper).length > 0) {
            $(this.template).appendTo($(this.wrapper));
        } else {
            $(this.template).appendTo($("body"));
        }
        
        this.onLoading();

        if (this.templateFile !== null && this.templateFile !== '' && this.templateFile !== undefined) {
            var url = PathHandler.combine(Config.htmlTemplateUrl, this.templateFile);
            var ctr = this;
            System.Core.Handler.RequestHandler.get(
                url,
                {},
                function(data) {
                    ctr.innerHtml = System.Core.Handler.RequestHandler.getResponseData(data);
                    ctr.renderControl(wrapper);
                }
            );
        } else {
            this.renderControl(wrapper);
        }

    },
    // methods was called after control was render
    onRendered: function() { },
    // methods was called before control was refreshed
    onRefreshing: function() { },
    // refresh control after refreshInterval milisecond 
    refresh: function() { },
    // methods was called after control was refreshed
    onRefreshed: function() { },
    /* return reference to control that has id match with expected controlId
    isRecursive: true to find in child control of current control
    return reference to control if found, otherwise return null or undefined*/
    findById: function(controlId, isRecursive) {
        // return null if control ha no child control
        if (this.controls.length <= 0) { return null; }
        for (var index in this.controls) {
            var ctr = this.controls[index];
            // return if found
            if (ctr && ctr.id === controlId) { return ctr; }
        }
        // control was not sound in child control  and not continue to find in child controls
        if (!isRecursive) { return null; }
        // find in child controls
        for (var indexChild in this.controls) {
            var ctrChild = this.controls[indexChild];
            if (!ctrChild.findById) { continue; }
            var resultCtr = ctrChild.findById(controlId, isRecursive);
            // control was found
            if (resultCtr) { return resultCtr; }
        }
    },
    // distroy control
    destroy: function() {
        try {
            for (var index = 0; index < this.controls.length; index++) {
                if (!this.controls[index].destroy) { continue; }
                // render child control
                this.controls[index].destroy();
            }
            // refresh control list
            this.controls = new Array();
            /* destroy current control
            wraper container was not found*/
            if ($('#' + this.id).length === 0) { return; }
            $('#' + this.id).hide(200);
        } catch (e) {
            e.source = "baseContro.Destroy methods";
            ExceptionHandler.throwEx(e);
        }
    },
    loadControl: function(controlConstrcutor, config) {
        if (config.wrapper && $(config.wrapper).length > 0) {
            $(config.wrapper).html('');
        }
        var ctr = new controlConstrcutor(config);
        
        if(config.autoRender===true){
            ctr.render();
        }
        this.add(ctr);
    }
};
// static member. Indecate that number of control was created
System.Core.UI.BaseControl.numOfControl=0;